package top.wsuo.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * 在线人数监听器:
 * 	- 每当有一个人上线人数就+1
 * 	- 每当有一个人下线人数就-1
 */
@WebListener
public class OnlineNumberAdminListener implements HttpSessionAttributeListener {

    public void attributeAdded(HttpSessionBindingEvent event) {
        String name = event.getName();
        if (name.equals("user")) {
            ServletContext application = event.getSession().getServletContext();
            int num = (Integer) application.getAttribute("onlineNum") + 1;
            application.setAttribute("onlineNum", num);
            System.out.println("当前在线人数：" + num);
        }

    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        String name = event.getName();
        if (name.equals("user")) {
            ServletContext application = event.getSession().getServletContext();
            int num = (Integer) application.getAttribute("onlineNum") - 1;
            application.setAttribute("onlineNum", num);
            System.out.println("当前在线人数：" + num);
        }

    }

    public void attributeReplaced(HttpSessionBindingEvent arg0) {

    }

}
